package hk.xing.boot.utils;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @description: AES 工具类
 * @author tangzhaofeng
 * @version 1.0
 */
@Component
public class AESUtils {

    private static final String ALGORITHM = "AES";
    private static final String KEY = "k3qXZ7Pj9RvmYp1sT8uW6bNcQ2eH4aLw";


    public static String decrypt(String ciphertext) throws Exception {
        byte[] encryptedData = Base64.getDecoder().decode(ciphertext);
        byte[] key = KEY.getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedData);
        return new String(decryptedBytes);
    }

    public static String decrypt2(String encryptedText) throws Exception {
        // Base64解码
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);

        // 创建AES密钥
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), "AES");

        // 初始化Cipher（使用AES/CBC/PKCS5Padding模式）
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        // 解密
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        // 返回解密后的字符串
        return new String(decryptedBytes);
    }


    public static void main(String[] args) {
        try {
            String decryptedText2 = AESUtils.decrypt2("U2FsdGVkX18vWADislWedaBJRq0sz2HLiJC6LqYmkFs=");
            System.out.println("Decrypted text: " + decryptedText2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
